//
//  RHAddPlantViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/24.
//

#import "RHAddPlantViewController.h"
#import "NSString+YYUtil.h"
#import "LocationManager.h"
#import "RHAddPlantCell.h"
#import "UITableViewCell+Indicator.h"
#import "RHAddPlantCell.h"
#import "ChoicePlantTypeView.h"
#import "ChoiceAuthView.h"
#import "RHChoiceTimeZoneView.h"
#import "RHAddPlantModel.h"
#import "RHSelectUserVC.h"

@interface RHAddPlantViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic ,strong) QMUIButton *deleteBtnB;

@property (nonatomic ,strong) UIImageView *plantImg;


@property (nonatomic ,copy) NSString *uploadImgUrl;

@property (nonatomic, assign) BOOL isShowType;

@property (nonatomic, strong) NSArray *productTypeArr;

@property (nonatomic ,strong) NSArray *titleArr;

@property (nonatomic ,strong) NSArray *placeholdArr;

@property (nonatomic ,strong) RHUserModel *userModel;//所属用户
@end

@implementation RHAddPlantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"创建电站".rh_localized;
    [self createData];
    
    
    [self setupUI];
    [self getCurrentZone];
    //终端自动显示上级
    if ([PrivateMange share].currentUser.hierarchyCode >= UserRoleTypeTerminalUser) {
        [self getSuperAdmins];
    }
    
    kWeakSelf;
    [[LocationManager manager] setGeocodeLocationComp:^(CLPlacemark *place) {
        NSString *address = [NSString stringWithFormat:@"%@%@%@%@%@",SafeStr(place.country),SafeStr(place.administrativeArea),SafeStr(place.locality),SafeStr(place.subLocality),SafeStr([place.areasOfInterest firstObject])];
        for (RHAddPlantModel *plantModel in self.dataArr) {
            if([plantModel.tag isEqualToString:@"plant_address"]){
                plantModel.content = address;
                break;
            }
        }
        [self.tableView reloadData];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[LocationManager manager] startSerialLocation];
    });
}


- (void)setupUI{
    self.titleArr = @[@"电站名称".rh_localized,@"电站类型".rh_localized,@"电价配置".rh_localized,@"上级可以查看？".rh_localized,@"电站地址".rh_localized,@"电站时区".rh_localized,@"维护人员".rh_localized,@"联系方式".rh_localized];
    self.placeholdArr = @[@"请输入电站名称".rh_localized,@"请选择类型".rh_localized,@"请输入电价".rh_localized,@"请选择查看权限".rh_localized,@"请输入电站地址".rh_localized,@"请输入电站时区".rh_localized,@"请输入维护人".rh_localized,@"邮箱".rh_localized];
    
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHAddPlantCell class] forCellReuseIdentifier:@"RHAddPlantCell"];
    [self.view addSubview:_tableView];
    _tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0);
    _tableView.tableHeaderView = self.headerView;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
}

-(void)getCurrentZone
{
    //获取当前时区
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"Z";//只打印时区
    NSString *curDateString = [dateFormatter stringFromDate:[NSDate date]];
    curDateString = [curDateString stringByReplacingOccurrencesOfString:@"0" withString:@""];
    NSString *zone = [NSString stringWithFormat:@"UTC%@",curDateString];
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHAddPlantModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([plantModel.tag isEqualToString:@"plant_zone"]) {
            plantModel.content = zone;
            *stop = YES;
        }
    }];
    [self.tableView reloadData];
}

//电站维护人   上级用户
-(void)getSuperAdmins
{
    [BaseModel startGetWithCompletionAPIKey:H_getSuperAdmins argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSString *nickName = request.responseJSONObject[@"data"][@"nickname"];;
            NSString *email = request.responseJSONObject[@"data"][@"email"];;
            
            [self.dataArr enumerateObjectsUsingBlock:^(RHAddPlantModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([plantModel.tag isEqualToString:@"plant_contact_name"]) {
                    plantModel.content = nickName;
                }
                if ([plantModel.tag isEqualToString:@"plant_contact_phone"]) {
                    plantModel.content = email;
                }
            }];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

- (UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,300)];
        [_footerView setBackgroundColor:UIColor.clearColor];
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,200)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view round:5 RectCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight];
        [_footerView addSubview:view];
        
        
        QMUILabel *lab = [[QMUILabel alloc] init];
        [lab setText:@"上传电站图片".rh_localized];
        [lab setTextAlignment:NSTextAlignmentLeft];
        [lab setFont:[UIFont systemFontOfSize:14]];
        [lab setTextColor:kCOLOR_HEX(@"3F4443")];
        [_footerView addSubview:lab];
        
        
        QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [btn.layer setCornerRadius:8];
        [btn setBackgroundColor:kCOLOR_HEX(@"#F3F7FF")];
        //[btn setBackgroundImage:[UIImage imageNamed:@"mask_group"] forState:UIControlStateNormal];
        [btn setImagePosition:QMUIButtonImagePositionTop];
        [btn setImage:[UIImage imageNamed:@"kwt_plant_camera"] forState:UIControlStateNormal];
        [btn setTitle:@"添加图片".rh_localized forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [btn setSpacingBetweenImageAndTitle:5];
        [btn setTitleColor:kCOLOR_HEX(@"AAAAAA") forState:UIControlStateNormal];
        [_footerView addSubview:btn];
        [btn addTarget:self action:@selector(addPicAction) forControlEvents:UIControlEventTouchUpInside];

        
        QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [createBtn setTitle:@"创建".rh_localized forState:UIControlStateNormal];
        [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [createBtn.layer setCornerRadius:8];
        [createBtn setBackgroundColor:CMainColorGreen];
        [_footerView addSubview:createBtn];
        [createBtn addTarget:self action:@selector(uploadHeadImage) forControlEvents:UIControlEventTouchUpInside];
        
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(30);
            make.top.mas_offset(15);
            make.right.mas_offset(-30);
            make.height.mas_equalTo(20);
        }];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(90, 90));
            make.left.equalTo(lab);
            make.top.equalTo(lab.mas_bottom).offset(10);
        }];
        
        [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.height.mas_equalTo(50);
            make.bottom.mas_offset(-15);
        }];
        
        kWeakSelf;
        _plantImg = kImageView;
        _plantImg.contentMode = UIViewContentModeScaleAspectFill;
        _plantImg.layer.cornerRadius = 8;
        _plantImg.layer.masksToBounds = YES;
        [_footerView addSubview:_plantImg];
        _plantImg.hidden = YES;
        
        [_plantImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(btn);
        }];
        
        QMUIButton *deleteBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [deleteBtn setImage:[UIImage imageNamed:@"kwt_pic_delete"] forState:UIControlStateNormal];
        [deleteBtn setBackgroundColor:UIColor.clearColor];
        [_footerView addSubview:deleteBtn];
        self.deleteBtnB = deleteBtn;
        self.deleteBtnB.hidden = YES;
        
        [[deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.plantImg.image = nil;
            weakSelf.plantImg.hidden = YES;
            weakSelf.deleteBtnB.hidden = YES;
            weakSelf.uploadImgUrl = nil;
        }];
        
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 30));
            make.right.equalTo(btn).offset(10);
            make.top.equalTo(btn).offset(-10);
        }];
    }
    return _footerView;
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,10)];
        [_headerView setBackgroundColor:UIColor.clearColor];
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,20)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view round:8 RectCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
        [_headerView addSubview:view];
        _headerView.clipsToBounds = YES;
    }
    return _headerView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 0)];
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 300;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return self.footerView;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddPlantCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAddPlantCell"];
    RHAddPlantModel *plantModel = self.dataArr[indexPath.row];
    cell.plantModel = plantModel;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    kWeakSelf;
    
    __weak __typeof(cell) weakCell = cell;
    cell.clickBlock = ^{
        if([plantModel.tag isEqualToString:@"plant_type"]){
            [weakSelf.view endEditing:YES];
            [weakSelf getPlantType:plantModel];
        }else if([plantModel.tag isEqualToString:@"plant_auth"]){
            [weakSelf.view endEditing:YES];
            [weakSelf createAuthData:plantModel];
        }else if([plantModel.tag isEqualToString:@"plant_zone"]){
            [weakSelf.view endEditing:YES];
           [weakSelf showTimeZoneList:plantModel];
        }else if([plantModel.tag isEqualToString:@"plant_user"]){
            [weakSelf.view endEditing:YES];
            [weakSelf selectUser:plantModel];
        }
        
    };
    return cell;
}


#pragma mark ------ 选择时区 -------
-(void)showTimeZoneList:(RHAddPlantModel*)plantModel;
{
    RHChoiceTimeZoneView *choiceView = [[RHChoiceTimeZoneView alloc] init];
    choiceView.titleLab.text = @"请选择电站时区".rh_localized;
    choiceView.curTimeZone = plantModel.content;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(NSString * _Nonnull zone) {
        if (zone == nil) {
            return;
        }
        plantModel.content = zone;
        [weakSelf.tableView reloadData];
    };
}


#pragma mark -------  //添加电站 提交--------------
-(void)addPlant
{
    kWeakSelf;
    //前面已做过判断
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [self.dataArr enumerateObjectsUsingBlock:^(RHAddPlantModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if (plantModel.content.length>0) {
            
            [para setObject:plantModel.content forKey:plantModel.key];
            if([plantModel.tag isEqualToString:@"plant_user"] && weakSelf.userModel){
                [para setObject:@(weakSelf.userModel.userId) forKey:plantModel.key];
            }
        }
    }];
    
    
    [QMUITips showLoading:@"添加电站...".rh_localized inView:self.view];

    if(self.uploadImgUrl){
        [para setObject:self.uploadImgUrl forKey:@"imageUrl"];
    }
    
    [BaseModel startWithCompletionAPIKey:H_addPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:PlantListNeedUpdateNotification object:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}

#pragma mark -------- 获取电站类型
-(void)getPlantType:(RHAddPlantModel*)plantModel
{
    [QMUITips showLoadingInView:self.view];
    [RHPlantTypeModel startGetWithCompletionAPIKey:H_plantTypeAndProductTypeRelation argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
    
            self.productTypeArr = resultModel.data;
            [self showPlantTypeList:plantModel];
            
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)createAuthData:(RHAddPlantModel*)plantModel
{
    ChoiceAuthView *choiceView = [[ChoiceAuthView alloc]init];
    choiceView.titleLab.text = @"请选择权限".rh_localized;
    choiceView.authList = plantModel.optionList;
    choiceView.curAuth = plantModel.content;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(RHOptionModel * _Nonnull model) {
        if (model==nil) {
            return;
        }
        plantModel.content = [NSString stringWithFormat:@"%ld",model.typeId];
        [weakSelf.tableView reloadData];
    };
}


-(void)showPlantTypeList:(RHAddPlantModel*)plantModel
{
    ChoicePlantTypeView *choiceView = [[ChoicePlantTypeView alloc] init];
    choiceView.plantTypeList = self.productTypeArr;
    choiceView.curType = plantModel.content;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(RHPlantTypeModel * _Nonnull model) {
        if (model == nil) {
            return;
        }
        plantModel.content = model.plantType;
        [weakSelf.tableView reloadData];
    };
}

-(void)selectUser:(RHAddPlantModel*)plantModel
{
    RHSelectUserVC *userVC = [[RHSelectUserVC alloc]init];
    kWeakSelf;
    userVC.selectBlock = ^(RHUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        plantModel.content = userModel.email;
        //如果是管理层,选了终端用户后带出上级
        for (RHAddPlantModel *plantModel in weakSelf.dataArr) {
            if ([plantModel.tag isEqualToString:@"plant_contact_name"]) {
                plantModel.content = userModel.superUsername;
            }
            if ([plantModel.tag isEqualToString:@"plant_contact_phone"]) {
                plantModel.content = userModel.superAdminEmail;
            }
        }
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:userVC animated:YES];
}

-(NSString*)getTextFromCellIndex:(NSInteger)index
{
    RHAddPlantCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    return cell.textField.text;
   
}


#pragma mark - Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"拍照".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.plantImg.hidden = NO;
        weakSelf.plantImg.image = image;
       
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = NO;
    
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = kCOLOR_HEX(@"#FFFFFF");;
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
    
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        
        UIImage *image = images[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
        NSLog(@"--->图片大小: %ld k", (long)(imageData.length / 1024));
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.plantImg.hidden = NO;
        weakSelf.plantImg.image = image;
        
    
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}




#pragma mark -------- 图片上传 ----------------
-(void)uploadHeadImage
{
    
    __block BOOL isCheckOK = YES;
    [self.dataArr enumerateObjectsUsingBlock:^(RHAddPlantModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([plantModel.tag isEqualToString:@"plant_name"]) {
            if(plantModel.content.length<4){
                [QMUITips showError:@"电站名称请输入4至32个字符".rh_localized];
                isCheckOK = NO;
                *stop = YES;
                return;
            }
        }
        if ([plantModel.tag isEqualToString:@"plant_address"]) {
            if( plantModel.content.length<2||plantModel.content.length>64){
                [QMUITips showError:@"电站地址请输入2至64个字符".rh_localized];
                isCheckOK = NO;
                *stop = YES;
                return;
            }
        }
        
        if ([plantModel.tag isEqualToString:@"plant_contact_name"]||
            [plantModel.tag isEqualToString:@"plant_contact_phone"]) {
            if(plantModel.content.length == 0){
                [QMUITips showLoading:@"获取维护人信息...".rh_localized inView:self.view];
                [self getSuperAdmins];
                isCheckOK = NO;
                *stop = YES;
                return;
            }
        }
        
        
        if (plantModel.isRequired && plantModel.content.length == 0) {
            [QMUITips showInfo:plantModel.placeHolder];
            isCheckOK = NO;
            *stop = YES;
        }
    }];
    
    if (isCheckOK == NO) {
        return;
    }
    

    if(self.plantImg.image == nil){
      
        [self addPlant];
        return;
    }
    kWeakSelf;
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
    UIImage *image = self.plantImg.image;
    //压缩到500K
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *compressImg = [self compressImageQuality:image toByte:2000];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:weakSelf.view];
            //清除上次上传的
            weakSelf.uploadImgUrl = nil;
            //上传头像
            [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
            [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios"} image:compressImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                if(resultModel.code == 200){
                    //保存图片参数
                    weakSelf.uploadImgUrl = request.responseObject[@"url"];
                   
                    [weakSelf addPlant];
                    
                }
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
               
                
            }];
        });
    });

    
}

//压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}

-(void)createData
{

    NSMutableArray *datas = @[
        @{@"title":@"电站名称".rh_localized,
          @"placeHolder":@"请输入电站名称".rh_localized,
          @"maxLength":@(32),
          @"isRequired":@(1),
          @"tag":@"plant_name",
          @"isFirst":@(1),
          @"key":@"plantName",
          @"canEdit":@(1)
        },
        @{@"title":@"电站类型".rh_localized,
          @"placeHolder":@"请选择电站类型".rh_localized,
          @"maxLength":@(32),
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_type",
          @"key":@"plantType"
        },
        @{@"title":@"电价配置".rh_localized,
          @"placeHolder":@"请输入电价".rh_localized,
          @"maxLength":@(10),
          @"tag":@"plant_price",
          @"key":@"price",
          @"canEdit":@(1)
        },
        @{@"title":@"上级可以查看？".rh_localized,
          @"placeHolder":@"请选择查看权限".rh_localized,
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(0),
                  @"typeName":@"否".rh_localized
              },
              @{
                  @"typeId":@(1),
                  @"typeName":@"是".rh_localized
              }
          ],
          @"isRequired":@(1),
          @"tag":@"plant_auth",
          @"key":@"authorization"
        },
        @{@"title":@"电站地址".rh_localized,
          @"placeHolder":@"请输入电站地址".rh_localized,
          @"maxLength":@(64),
          @"isRequired":@(1),
          @"tag":@"plant_address",
          @"key":@"address",
          @"canEdit":@(1)
        },
        @{@"title":@"电站时区".rh_localized,
          @"placeHolder":@"请输入电站时区".rh_localized,
          @"isRequired":@(1),
          @"isSelection":@(1),
          @"tag":@"plant_zone",
          @"key":@"timezone"
        },
        @{@"title":@"维护人员".rh_localized,
          @"placeHolder":@"请输入维护人".rh_localized,
          @"isRequired":@(1),
          @"tag":@"plant_contact_name",
          @"key":@"maintenance"
        },
        @{@"title":@"联系方式".rh_localized,
          @"placeHolder":@"邮箱".rh_localized,
          @"isRequired":@(1),
          @"tag":@"plant_contact_phone",
          @"key":@"email"
        }
       
    ].mutableCopy;
    //终端以上管理层级 可以为下级的所有终端用户创建电站
    if ([PrivateMange share].currentUser.hierarchyCode < UserRoleTypeTerminalUser) {
        NSDictionary *userDic = @{
                                  @"title":@"所属用户".rh_localized,
                                  @"placeHolder":@"请选择所属用户".rh_localized,
                                  @"isRequired":@(1),
                                  @"isSelection":@(1),
                                  @"tag":@"plant_user",
                                  @"key":@"userId"
        };
        [datas insertObject:userDic atIndex:datas.count-2];
    }
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHAddPlantModel class] json:datas];
}

@end
